package com.trade.dao.listener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.trade.dao.impl.*;
import com.trade.dao.IEquityDAO;
import com.trade.data.EquityHistoricalDataVO;
import com.trade.data.EquityIntradayDataVO;
import com.trade.data.HistoricalDataVO;
import com.trade.data.IndexIntradayDataVO;

import net.esper.client.UpdateListener;
import net.esper.event.EventBean;

public class PriceUpdateListener extends BaseDAO implements UpdateListener {

	Session session = null ;
	private static IEquityDAO equityDAO;

	public static void setEquityDAO(IEquityDAO pEquityDAO) {
		equityDAO = pEquityDAO;
	}

	public void update(EventBean[] newData, EventBean[] oldData) {
		if( newData[0].getUnderlying() instanceof EquityIntradayDataVO){
			System.out.println("Price Received : " + newData[0].getUnderlying());
			//System.out.println("Equity Intraday : ");
			try {
				HistoricalDataVO updatedDataVO = (HistoricalDataVO)newData[0].getUnderlying();
				List<HistoricalDataVO> list= new ArrayList<HistoricalDataVO>();
				list.add(updatedDataVO);
				equityDAO.addIntradayDataInCache( list );


				//Calculate Gain or Loss
				HistoricalDataVO currentDataVO = (HistoricalDataVO)newData[0].getUnderlying();
				if( oldData != null){
					HistoricalDataVO oldDataVO = (HistoricalDataVO)oldData[0].getUnderlying();
					Double gainOrLoss = currentDataVO.getClose() - oldDataVO.getClose();
					HistoricalDataVO gainVO = new HistoricalDataVO();
					HistoricalDataVO lossVO = new HistoricalDataVO();

					gainVO.setSymbol(updatedDataVO.getSymbol());
					gainVO.setClose(updatedDataVO.getClose());

					lossVO.setSymbol(updatedDataVO.getSymbol());
					lossVO.setClose(updatedDataVO.getClose());

					if( gainOrLoss > 0 ){
						gainVO.setCalValue(gainOrLoss);
						equityDAO.addEquityGainIntradayHistoricalData(gainVO);

						lossVO.setCalValue(0d);
						equityDAO.addEquityLossIntradayHistoricalData(lossVO);
					}else{
						lossVO.setCalValue(-gainOrLoss);
						equityDAO.addEquityLossIntradayHistoricalData(lossVO);

						gainVO.setCalValue(0d);
						equityDAO.addEquityGainIntradayHistoricalData(gainVO);
					}

					//System.out.println("Equity Intraday Gain or Loss : "+gainOrLoss);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if( newData[0].getUnderlying() instanceof IndexIntradayDataVO){
			//System.out.println("Index Intraday : ");
		}


	}
}
